#!/usr/local/bin/python
# -*- coding: utf-8 -*-


from datetime import datetime

from PyQt5.QtCore import QUrl
from dateutil.relativedelta import relativedelta


from PyQt5.QtWidgets import QWidget
from xToolkit import xstring

import init
import initLogger

import toolkit
from data_alchemy.account_book_alchemy import AccountBookAlchemy
from data_alchemy.balance_sheet_monthly_alchemy import BalanceSheetMonthlyAlchemy
from data_alchemy.cash_flow_monthly_alchemy import CashFlowMonthlyAlchemy
from data_alchemy.income_statement_monthly_alchemy import IncomeStatementMonthlyAlchemy

from html_echarts.initStatisticalChart import  STATISTICAL_CHART_HTML


from ui.StatisticalChartUI_new import Ui_StatisticalChart
'''
1、月度收支表：没有收入支出情况；
2、净资产表：每月净资产的变化情况；
3、每月结余表：每月结余的金额，有可能是负数；

'''

class StatisticalChartWidget(QWidget, Ui_StatisticalChart):
    def __init__(self):
        super(StatisticalChartWidget, self).__init__()
        self.setupUi(self)

        self.currentDate = datetime.now()  #记录当前事件
        self.targetDate = self.currentDate  - relativedelta(days=init.GO_DAYS)#记录当前系统查看数据的时间
        self.htmlJsonData= {} #推动到html图表页面的数据。

        self.initStatisticalChartTitleUI()
        self.initStatisticalChart()

    def initStatisticalChartTitleUI(self):
        '''
        函数功能：对统计图表页面的标题进行初始化
        :return:
        '''
        titleStr="%d年统计图表"%( self.targetDate.year )
        self.title_label.setText(titleStr)

    def initStatisticalChart(self):
        '''
        函数功能：初始化统计页面报表
        :return:
        '''
        #self.showIndicatorBoardStatementChart()
        self.showWebChartView()
        # self.showBalanceSheetChart()
        # self.showDebtChart()
        # self.showCashFlowChart()



    def onGoLastYear(self):
        '''
        函数功能：查看上一年数据
        :return:
        '''

        initLogger.logger.debug("call onGoLastYear function")

        self.targetDate = toolkit.getLastYear(self.targetDate, number=1)
        initLogger.logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))


        self.initStatisticalChartTitleUI()

        # self.showIndicatorBoardStatementChart()
        self.showWebChartView()
        # self.showBalanceSheetChart()
        # self.showDebtChart()
        # self.showCashFlowChart()


    def onGoNextYear(self):
        '''
        函数功能：查看下一年数据
        :return:
        '''

        initLogger.logger.debug("call onGoNextYear function")

        self.targetDate = toolkit.getNextYear(self.targetDate, number=1)
        initLogger.logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))

        self.initStatisticalChartTitleUI()

        # self.showIndicatorBoardStatementChart()
        self.showWebChartView()
        # self.showBalanceSheetChart()
        # self.showDebtChart()
        # self.showCashFlowChart()



    def showWebChartView(self):
        '''
        函数功能：展示收支表柱形图
        :return:
        '''
        initLogger.logger.debug("call showIncomeStatementChart function")
        #self.webChartView.setHtml(INCOME_STATEMENT_CHART_HTML)
        self.webChartView.setHtml(STATISTICAL_CHART_HTML)
        self.webChartView.loadFinished.connect(self.pushWebChartJsonpData)


    def genIndicatorBoardStatementChart(self):
        '''
        函数功能：生成指标看板数据
        :return:
        '''

        initLogger.logger.debug("call genIndicatorBoardStatementChart function")
        self.htmlJsonData["indicator_board_value"] = {
            "total_property":0.00,
            "income": 0.00,
            "expense": 0.00,
            "surplus":0.00
        }

        balanceSheetMonthlyAlchemy = BalanceSheetMonthlyAlchemy()
        incomeStatementAlchemy = IncomeStatementMonthlyAlchemy()

        totalPropertyValue = balanceSheetMonthlyAlchemy.GetLatestPropertyValueByYear(self.targetDate.year)
        if totalPropertyValue !=None:
            self.htmlJsonData["indicator_board_value"]["total_property"]= totalPropertyValue

        incomeValue = incomeStatementAlchemy.GetLatestIncomeValueByYear(self.targetDate.year)
        if incomeValue != None:
            self.htmlJsonData["indicator_board_value"]["income"] = incomeValue

        expenseValue = incomeStatementAlchemy.GetLatestExpenseValueByYear(self.targetDate.year)
        if expenseValue != None:
            self.htmlJsonData["indicator_board_value"]["expense"] = expenseValue

        if incomeValue != None and expenseValue != None:
            self.htmlJsonData["indicator_board_value"]["surplus"] = self.htmlJsonData["indicator_board_value"]["income"] - self.htmlJsonData["indicator_board_value"]["expense"]

    def genIncomeStatementChartDataByMonth(self):
        '''
        函数功能：生成收支表数据推送给Echarts图表
        :return:
        '''

        initLogger.logger.debug("call genIncomeStatementChartDataByMonth function")
        self.htmlJsonData["income_statement_value"]  = {
            "date_time": ["", "", "", "", "", "", "", "", "", "", "", ""],
            "income": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
            "expense": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
        }

        incomeStatementAlchemy = IncomeStatementMonthlyAlchemy()
        incomeStatementAlchemyList = incomeStatementAlchemy.SearchIncomeStatementByYear(self.targetDate.year)

        # initLogger.logger.debug("incomeStatementAlchemyList:%s"%(incomeStatementAlchemyList))

        for j in range(12):
            self.htmlJsonData["income_statement_value"]["date_time"][j] = "%d.%02d" % (self.targetDate.year, j + 1)

        for i in range(len(incomeStatementAlchemyList)):
            incomeStatementAlchemyItem = incomeStatementAlchemyList[i]
            if incomeStatementAlchemyItem.data_type == "收入":

                self.htmlJsonData["income_statement_value"]["income"][
                    incomeStatementAlchemyItem.month - 1] = incomeStatementAlchemyItem.current_month_value
            elif incomeStatementAlchemyItem.data_type == "支出":
                self.htmlJsonData["income_statement_value"]["expense"][
                    incomeStatementAlchemyItem.month - 1] = incomeStatementAlchemyItem.current_month_value
            else:
                # 处理其他情况
                pass

    def genCashFlowDataByMonth(self):
        '''
        函数功能：生成现金流数据推送给Echarts图表
        :return:
        '''

        initLogger.logger.debug("call genCashFlowDataByMonth function")
        self.htmlJsonData["cash_flow_value"] = {
            "date_time": ["", "", "", "", "", "", "", "", "", "", "", ""],
            "inflow": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
            "outflow": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
        }

        cashFlowMonthlyAlchemy = CashFlowMonthlyAlchemy()
        cashFlowMonthlyAlchemyList = cashFlowMonthlyAlchemy.SearchCashFlowOwnershipByYear(self.targetDate.year)

        for j in range(12):
            self.htmlJsonData["cash_flow_value"]["date_time"][j] = "%d.%02d" % (self.targetDate.year, j + 1)

        for i in range(len(cashFlowMonthlyAlchemyList)):
            cashFlowMonthlyAlchemyItem = cashFlowMonthlyAlchemyList[i]

            self.htmlJsonData["cash_flow_value"]["inflow"][
                    cashFlowMonthlyAlchemyItem.month - 1] = cashFlowMonthlyAlchemyItem.inflow_value
            self.htmlJsonData["cash_flow_value"]["outflow"][
                    cashFlowMonthlyAlchemyItem.month - 1] = cashFlowMonthlyAlchemyItem.outflow_value


    def genBalanceSheetChartDataByMonth(self):
        '''
        函数功能：将指定年份的资产变动趋势数据推送给Echarts图表
        :return:
        '''


        initLogger.logger.debug("call genBalanceSheetChartDataByMonth function")
        self.htmlJsonData["balance_sheet_value"]= {
            "min_value":0,
            "date_time": ["", "", "", "", "", "", "", "", "", "", "", ""],
            "property_value": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
        }

        #设置月份信息数据
        for j in range(12):
            self.htmlJsonData["balance_sheet_value"]["date_time"][j] = "%d.%02d" % (self.targetDate.year, j + 1)

        balanceSheetMonthlyAlchemy = BalanceSheetMonthlyAlchemy()
        balanceSheetMonthlyAlchemyList = balanceSheetMonthlyAlchemy.SearchBalanceSheetPropertyByYear(self.targetDate.year)


        #初始化各月的资产金额
        for i in range(len(balanceSheetMonthlyAlchemyList)):
            balanceSheetMonthlyAlchemyItem = balanceSheetMonthlyAlchemyList[i]
            self.htmlJsonData["balance_sheet_value"]["property_value"][balanceSheetMonthlyAlchemyItem.month-1] = balanceSheetMonthlyAlchemyItem.end_value

        minValue= toolkit.specialMinValue(self.htmlJsonData["balance_sheet_value"]["property_value"])
        self.htmlJsonData["balance_sheet_value"]["min_value"]=int(minValue/100000-1)*100000

    def genDebtChartDataByMonth(self):
        '''
        函数功能：将指定年份的各月负债的数据推送给Echarts图表
        :return:
        '''

        initLogger.logger.debug("call genDebtChartDataByMonth function")
        self.htmlJsonData["debt_value"] = {
            "date_time": ["", "", "", "", "", "", "", "", "", "", "", ""],
            "huabei": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
            "credit": [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
        }

        for j in range(12):
            self.htmlJsonData["debt_value"] ["date_time"][j] = "%d.%02d" % (self.targetDate.year, j + 1)

        accountBookAlchemy = AccountBookAlchemy()
        accountBookAlchemyList = accountBookAlchemy.GetDebtDateByYear(self.targetDate.year)

        for i in range(len(accountBookAlchemyList)):
            accountBookAlchemyItem = accountBookAlchemyList[i]
            if accountBookAlchemyItem.subject_name_2 == "蚂蚁花呗":
                self.htmlJsonData["debt_value"] ["huabei"][accountBookAlchemyItem.month - 1] = accountBookAlchemyItem.increase_value
            elif accountBookAlchemyItem.subject_name_2 == "信用卡":
                self.htmlJsonData["debt_value"] ["credit"][accountBookAlchemyItem.month - 1] = accountBookAlchemyItem.increase_value
            else:
                initLogger.logger.warn("wrong data in pushDebtChartDataByYear function")




    def pushWebChartJsonpData(self):
        '''
        函数功能：将指定年份的所有数据推送给Echarts图表
        :return:
        '''

        initLogger.logger.debug("call pushWebChartJsonpData function")

        self.genIndicatorBoardStatementChart()  #生成月度指标看板数据
        self.genBalanceSheetChartDataByMonth()  # 生成月度资产负债表数据
        self.genIncomeStatementChartDataByMonth()  #生成月度收支表数据
        self.genCashFlowDataByMonth()  #生成月度现金流表数据
        self.genDebtChartDataByMonth() #生成月度负债数据

        jscode = "getJson({})".format(self.htmlJsonData)
        self.webChartView.page().runJavaScript(jscode)


